import React, { Component } from 'react'
import { Flex, WingBlank, WhiteSpace, Toast } from 'antd-mobile'

import { Link } from 'react-router-dom'

import NavHeader from '../../components/NavHeader'
import { API } from '../../utils'
import { BASE_URL } from '../../utils'

import styles from './index.module.scss'

import { withFormik, Form, Field, ErrorMessage } from 'formik'

import * as Yup from 'yup'

// 检验规则
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/

class Login extends Component {
  render() {
    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavHeader className={styles.navHeader}>登录</NavHeader>

        {/* 登录表单 */}
        <WingBlank>
          <Form>
            <div className={styles.formItem}>
              <Field className={styles.input} name="username" placeholder="请输入账号" ></Field>
            </div>
            <ErrorMessage className={styles.error} name="username" component="div"></ErrorMessage>
            {/* <div className={styles.error}>账号为必填项</div> */}

            <div className={styles.formItem}>
              <Field className={styles.input} name="password" placeholder="请输入密码" type="password"></Field>
            </div>
            <ErrorMessage className={styles.error} name="password" component="div"></ErrorMessage>
            {/* <div className={styles.error}>密码为必填项</div> */}

            <div className={styles.formSubmit}>
              <button className={styles.submit} type="submit">登录</button>
            </div>
          </Form>

          <Flex className={styles.backHome}>
            <Flex.Item>
              <Link to="/register">还没有账号，先去注册一个~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}

// 包装Login组件
Login = withFormik({
  // 提供状态：
  mapPropsToValues: () => ({ username: '', password: '' }),

  // 添加表单检验规则
  validationSchema: Yup.object().shape({
    username: Yup.string().required('账号为必填项').matches(REG_UNAME, '长度为5~8位，只能出现数字、字母、下划线'),
    password: Yup.string().required('密码为必填项').matches(REG_UNAME, '长度为5~12位，只能出现数字、字母、下划线')
  }),

  // 表单的提交事件
  handleSubmit: async (values, { props }) => {
    // console.log("Formik", values)
    const { username, password } = values

    const res = await API.post('/user/login', {
      username,
      password
    })

    const { status, body, description } = res.data
    console.log(values, res.data)
    if (status === 200) {
      // 登录成功
      localStorage.setItem('hkzf_token', body.token)

      // 注意：无法在这用this获取路由信息，只能调用参数props
      // 这是登录成功后的跳转
      if (!props.location.state) {
        // 直接进入登录页，登录成功后倒退就行
        props.history.go(-1)
      } else {
        // 路由导航进来的，登录成功后要进入导航的目标路径
        props.history.replace(props.location.state.from.pathname)
      }
    } else {
      // 登录失败
      Toast.info(description, 2, null, false)
    }
  }
})(Login)

export default Login